<?php

namespace app\server;



class XwechatServerServer
{
    public function getWxPath($wxName,$dumpPath){
        $path = '';
        if($wxName === 'xinglin'){
            try{
                $response = curlData('https://api.yqdhz.com/api/extra/wxPath?wx_name='.$wxName);
                $res = json_decode($response,true);
                if(!empty($res['data'][0]['openlink'])){
                    $path = $res['data'][0]['openlink'];
                }
            }catch(\Exception $e){}
        }else{
            $res = $this->scheme($wxName,$dumpPath);
            if($res['errcode'] === 0){
                $path = $res['openlink'];
            }
        }
        return $path;
    }

    public function scheme($appName,$path){
        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $this->getAccessToken($appName);
        $content = [
            'jump_wxa'=>[
                'path'=>$path,
                'query'=>'',
                'env_version'=>'release'
            ]
        ];
        $postString = json_encode($content);
        $header = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($postString),
        ];
        $response = curlData($url, $postString, 'POST', '', $header);
        return json_decode($response, true);

    }

    /**
     * 获取用户openid
     * @param $appName
     * @param $code
     * @return mixed
     */
    public function getUserOpenId($appName, $code)
    {
        $wechatConfig = config($appName . '.wechat');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wechatConfig['app_id'] . '&secret=' .$wechatConfig['app_secret']. '&js_code=' . $code . '&grant_type=authorization_code';
        $response = curlData($url, [], 'GET');
        addDebugLog('token',['url'=>$url,'response'=>$response]);
        return json_decode($response, true);
    }

    /**
     * 获取accessToken
     * @param $appName
     * @return mixed|object|\think\App
     */
    public function getAccessToken($appName)
    {
        $key = $appName . ":access_token";
        $accessToken = cache($key);
        if (!empty($accessToken)) {
            return $accessToken;
        } else {
            $wechatConfig = config($appName . '.wechat');
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wechatConfig['app_id'] . '&secret=' . $wechatConfig['app_secret'];
            $response = curlData($url, [], 'GET');
            $response = json_decode($response, true);
            $accessToken = $response['access_token'];
            cache($key, $accessToken, 7000);
            return $accessToken;
        }
    }

}


?>
